import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yqmssa_app/config/app_config.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebView extends StatefulWidget {
  const WebView({super.key});

  @override
  State<WebView> createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  late Map<String, String?> data = Get.parameters;

  late WebViewController controller;

  late String title = data["title"] ?? "";

  ValueNotifier<bool> isLoading = ValueNotifier(true);

  @override
  void initState() {
    super.initState();
    init();
  }

  init() {
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.transparent)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {
            // Page started loading.
            debugPrint(url);
          },
          onPageFinished: (String url) {
            if (data.isEmpty) getTitle();
            isLoading.value = false;
          },
          onWebResourceError: (WebResourceError error) {
            // Handle web resource error.
          },
        ),
      )
      ..loadRequest(Uri.parse(data.isEmpty ? 'https://beian.miit.gov.cn/' : (data["url"] ?? '')));
    setState(() {});
  }

  getTitle() async {
    final t = await controller.getTitle();
    if (t != null && t.isNotEmpty) {
      setState(() {
        title = t;
      });
    }
  }

  showMenuTop() {
    showMenu(
      context: context,
      position: const RelativeRect.fromLTRB(100, 10, 0, 0),
      items: [
        const PopupMenuItem(
          value: 'copy',
          child: Text('复制链接'),
        ),
        const PopupMenuItem(
          value: 'launch',
          child: Text('在浏览器打开'),
        ),
      ],
    ).then((value) {
      if (value == 'share') {
        // Handle share action
      } else if (value == 'copy') {
        // Handle copy action
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(title),
          leading: IconButton(onPressed: Get.back, icon: const Icon(Icons.arrow_back_ios, color: Colors.black)),
          actions: [
            if (data.isEmpty)
              PopupMenuButton<String>(
                color: Colors.white,
                surfaceTintColor: Colors.white,
                itemBuilder: (context) {
                  return const [
                    PopupMenuItem<String>(
                      value: 'copy',
                      child: Row(
                        children: [
                          Icon(Icons.link),
                          SizedBox(width: 8),
                          Text('复制链接'),
                        ],
                      ),
                    ),
                    PopupMenuItem(
                      value: 'launch',
                      child: Row(
                        children: [
                          Icon(Icons.launch),
                          SizedBox(width: 8),
                          Text('在浏览器打开'),
                        ],
                      ),
                    ),
                  ];
                },
                shape: ContinuousRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                onSelected: (val) {
                  if (val == 'copy') {
                    // 复制链接
                    Clipboard.setData(const ClipboardData(text: "https://beian.miit.gov.cn/"));
                    SmartDialog.showToast(
                      "复制成功",
                      alignment: Alignment.topCenter,
                      displayTime: const Duration(seconds: 2),
                    );
                  } else if (val == 'launch') {
                    // 在浏览器打开
                    AppConfig.launchLink("https://beian.miit.gov.cn/");
                  }
                },
              ),
          ],
        ),
        body: ValueListenableBuilder(
          valueListenable: isLoading,
          builder: (context, val, child) {
            if (val) {
              return const Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    CircularProgressIndicator(),
                    SizedBox(height: 12),
                    Text(
                      "加载中...",
                      style: TextStyle(fontSize: 16),
                    )
                  ],
                ),
              );
            } else {
              return child!;
            }
          },
          child: WebViewWidget(controller: controller),
        ));
  }
}
